package main

import (
	"github.com/go-kratos/kratos-layout/internal/conf"
	"github.com/go-kratos/kratos/contrib/config/apollo/v2"
	nacosconfig "github.com/go-kratos/kratos/contrib/config/nacos/v2"
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/config/file"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

func LoadConfigSequentially() config.Config {

	ss := []config.Source{file.NewSource(flagconf)}

	//1.load local config
	lf := config.WithSource(
		ss[0],
	)

	//1.load local file config
	lc := config.New(lf)
	if err := lc.Load(); err != nil {
		panic(err)
	}

	var bc conf.Bootstrap
	if err := lc.Scan(&bc); err != nil {
		lc.Close()
		panic(err)
	}

	lc.Close()

	//2.load eureka config
	if bc.Apollo != nil {
		ss = append(ss, apollo.NewSource(
			apollo.WithAppID(bc.Apollo.AppId),
			apollo.WithCluster(bc.Apollo.Cluster),
			apollo.WithEndpoint(bc.Apollo.Ip),
			apollo.WithEnableBackup(),
			apollo.WithNamespace(bc.Apollo.NamespaceName)))
	}

	//3.load nacos config
	if bc.Nacos != nil {
		client, err := clients.NewConfigClient(
			vo.NacosClientParam{
				ClientConfig: &constant.ClientConfig{
					NamespaceId:         bc.Nacos.Namespace,
					TimeoutMs:           5000,
					NotLoadCacheAtStart: true,
					LogDir:              "/tmp/nacos/log",
					CacheDir:            "/tmp/nacos/cache",
					RotateTime:          "1h",
					MaxAge:              3,
					LogLevel:            "debug",
				},
				ServerConfigs: []constant.ServerConfig{
					*constant.NewServerConfig(bc.Nacos.Ip, bc.Nacos.Port),
				},
			},
		)
		if err != nil {
			log.Error()
		}
		ss = append(ss, nacosconfig.NewConfigSource(client,
			nacosconfig.WithGroup(bc.Nacos.Group), nacosconfig.WithDataID(bc.Nacos.DataId)))
	}

	ac := config.New(config.WithSource(ss...))
	if err := ac.Load(); err != nil {
		lc.Close()
		panic(err)
	}
	return ac
}
